package com.tang.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.stream.Collectors;

/**
 * 全局异常处理
 *
 * @author JH
 */
@RestControllerAdvice
@Slf4j
public class GlobalController {
    /**
     * 参数校验异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
    public ResponseEntity<ResultData<String>> handleValidatedException(Exception e){
        ResultData<String> resp;
        if (e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            resp = ResultData.fail(HttpStatus.BAD_REQUEST.value(),ex.getBindingResult().getAllErrors().stream()
                    .map(ObjectError::getDefaultMessage).collect(Collectors.joining(",")));

        }else if (e instanceof ConstraintViolationException){
            ConstraintViolationException ex = (ConstraintViolationException) e;
            resp = ResultData.fail(HttpStatus.BAD_REQUEST.value(), ex.getConstraintViolations().stream()
                    .map(ConstraintViolation::getMessage).collect(Collectors.joining(",")));
        }else if (e instanceof BindException){
            BindException ex = (BindException) e;
            resp = ResultData.fail(HttpStatus.BAD_REQUEST.value(), ex.getAllErrors().stream()
                    .map(ObjectError::getDefaultMessage).collect(Collectors.joining(",")));
        }else {
            resp = ResultData.fail(HttpStatus.BAD_REQUEST.value(), e.getMessage());
        }

        return new ResponseEntity<>(resp,HttpStatus.BAD_REQUEST);
    }

    /**
     * 全局异常捕获处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultData<String> exception(Exception e){
        log.error("全局异常信息ex={}",e.getMessage(),e);
        return ResultData.fail(500,e.getMessage());
    }

}
